import _ from 'lodash';

// 单元格引用的正则表达式 (如 A1, B2, AA1 等)
const cellRefRegex = /^[A-Z]{1,2}[0-9]+$/;

// 报表引用信息接口
export interface ReportRefInfo {
  currentRefs: {
    cells: string[];
    ranges: string[];
  };
  otherSheetRefs: {
    [key: string]: {
      cells: string[];
      ranges: string[];
    };
  };
}

/**
 * 解析表达式中的单元格引用
 * 简化版本，使用正则表达式替代 Babel 解析
 */
export function parseCellRefs(expression: string): ReportRefInfo {
  const ret: ReportRefInfo = {
    currentRefs: {
      cells: [],
      ranges: []
    },
    otherSheetRefs: {}
  };

  // 移除所有空白字符
  expression = expression.replace(/\s/g, '');

  // 匹配独立的单元格引用 (如 A1, B2)
  const cellMatches = expression.match(/[A-Z]{1,2}[0-9]+(?!\w)/g) || [];
  ret.currentRefs.cells = cellMatches.filter(cell => cellRefRegex.test(cell));

  // 匹配工作表引用 (如 sheet1.A1 或 sheet1['B2'])
  const sheetRefPattern = /(\w+)\.([A-Z]{1,2}[0-9]+)|(\w+)\['([A-Z]{1,2}[0-9]+)'\]/g;
  let match;

  while ((match = sheetRefPattern.exec(expression)) !== null) {
    const sheetName = match[1] || match[3];
    const cellRef = match[2] || match[4];

    if (cellRefRegex.test(cellRef)) {
      if (!ret.otherSheetRefs[sheetName]) {
        ret.otherSheetRefs[sheetName] = {
          cells: [],
          ranges: []
        };
      }
      ret.otherSheetRefs[sheetName].cells.push(cellRef);
    }
  }

  // 去重处理
  return {
    currentRefs: {
      cells: _.uniq(ret.currentRefs.cells),
      ranges: []
    },
    otherSheetRefs: Object.fromEntries(
      Object.entries(ret.otherSheetRefs).map(([key, value]) => [key, {
        cells: _.uniq(value.cells),
        ranges: []
      }])
    )
  };
}